<template>
  <div class="price-history-view">
    <el-container>
      <el-header height="auto" class="page-header">
        <div class="header-content">
          <h2>商品价格历史</h2>
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>价格历史</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
      </el-header>

      <el-main>
        <!-- 搜索区域 -->
        <el-card shadow="hover" class="search-card">
          <el-form :inline="true" :model="searchForm" class="search-form">
            <el-form-item label="查询方式">
              <el-radio-group v-model="searchType">
                <el-radio-button label="id">商品ID</el-radio-button>
                <el-radio-button label="sn">商品编号</el-radio-button>
              </el-radio-group>
            </el-form-item>

            <el-form-item v-if="searchType === 'id'" label="商品ID">
              <el-input-number
                v-model="searchForm.product_id"
                :min="1"
                placeholder="请输入商品ID"
                style="width: 200px"
              />
            </el-form-item>

            <el-form-item v-else label="商品编号">
              <el-input
                v-model="searchForm.product_sn"
                placeholder="如: PHONE-IP15P-001"
                style="width: 250px"
                clearable
              />
            </el-form-item>

            <el-form-item label="查询天数">
              <el-select v-model="searchForm.days" style="width: 120px">
                <el-option label="最近7天" :value="7" />
                <el-option label="最近30天" :value="30" />
                <el-option label="最近90天" :value="90" />
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleSearch" :loading="loading" :icon="Search">
                查询
              </el-button>
              <el-button @click="handleReset" :icon="RefreshLeft">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="8" animated />
        </div>

        <!-- 结果展示 -->
        <div v-else-if="priceData" class="result-container">
          <!-- 商品信息 -->
          <el-card shadow="hover" class="product-info-card">
            <div class="product-info">
              <div class="product-name">
                <el-tag type="primary" size="large">{{ priceData.product_sn }}</el-tag>
                <h3>{{ priceData.product_name }}</h3>
              </div>
              <div class="product-price">
                <span class="current-price">¥{{ priceData.current_price.toFixed(2) }}</span>
              </div>
            </div>
          </el-card>

          <!-- 价格统计 -->
          <PriceStatistics
            :statistics="priceData.statistics"
            :current-price="priceData.current_price"
          />

          <!-- 价格图表 -->
          <el-card shadow="hover" class="chart-card">
            <template #header>
              <div class="card-header">
                <span>价格走势图</span>
                <el-tag type="info" size="small">共 {{ priceData.total }} 条记录</el-tag>
              </div>
            </template>
            <PriceChart
              :data="priceData.history"
              :current-price="priceData.current_price"
              height="500px"
            />
          </el-card>

          <!-- 价格历史表格 -->
          <el-card shadow="hover" class="table-card">
            <template #header>
              <span>价格历史明细</span>
            </template>
            <el-table :data="tableData" stripe style="width: 100%">
              <el-table-column prop="date" label="日期" width="120" />
              <el-table-column label="售价" width="120">
                <template #default="{ row }">
                  <span class="price-value">¥{{ row.price.toFixed(2) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="原价" width="120">
                <template #default="{ row }">
                  <span v-if="row.original_price" class="original-price">
                    ¥{{ row.original_price.toFixed(2) }}
                  </span>
                  <span v-else class="text-muted">-</span>
                </template>
              </el-table-column>
              <el-table-column label="折扣" width="100">
                <template #default="{ row }">
                  <el-tag v-if="row.original_price && row.original_price > row.price" type="success" size="small">
                    {{ ((row.price / row.original_price) * 10).toFixed(1) }}折
                  </el-tag>
                  <span v-else class="text-muted">-</span>
                </template>
              </el-table-column>
              <el-table-column prop="reason" label="备注" min-width="150">
                <template #default="{ row }">
                  <el-tag v-if="row.reason" :type="getReasonTagType(row.reason)" size="small">
                    {{ row.reason }}
                  </el-tag>
                  <span v-else class="text-muted">正常</span>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </div>

        <!-- 空状态 -->
        <el-empty
          v-else
          description="请输入商品信息进行查询"
          :image-size="200"
        />
      </el-main>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, RefreshLeft } from '@element-plus/icons-vue'
import { getPriceHistory } from '@/api/product'
import type { PriceHistoryResponse } from '@/api/product'
import PriceChart from '@/components/PriceChart.vue'
import PriceStatistics from '@/components/PriceStatistics.vue'

// 搜索类型
const searchType = ref<'id' | 'sn'>('id')

// 搜索表单
const searchForm = reactive({
  product_id: 1,
  product_sn: '',
  days: 30
})

// 加载状态
const loading = ref(false)

// 价格数据
const priceData = ref<PriceHistoryResponse | null>(null)

// 表格数据（倒序显示，最新的在前）
const tableData = computed(() => {
  if (!priceData.value) return []
  return [...priceData.value.history].reverse()
})

// 查询
const handleSearch = async () => {
  // 验证输入
  if (searchType.value === 'id' && !searchForm.product_id) {
    ElMessage.warning('请输入商品ID')
    return
  }
  if (searchType.value === 'sn' && !searchForm.product_sn) {
    ElMessage.warning('请输入商品编号')
    return
  }

  loading.value = true
  priceData.value = null

  try {
    const params: any = { days: searchForm.days }
    if (searchType.value === 'id') {
      params.product_id = searchForm.product_id
    } else {
      params.product_sn = searchForm.product_sn
    }

    const response = await getPriceHistory(params)
    priceData.value = response
    ElMessage.success('查询成功')
  } catch (error: any) {
    console.error('查询失败:', error)
    ElMessage.error(error.response?.data?.detail || '查询失败，请检查输入或稍后重试')
  } finally {
    loading.value = false
  }
}

// 重置
const handleReset = () => {
  searchForm.product_id = 1
  searchForm.product_sn = ''
  searchForm.days = 30
  priceData.value = null
}

// 获取备注标签类型
const getReasonTagType = (reason: string) => {
  if (reason.includes('促销') || reason.includes('大促') || reason.includes('秒杀') || reason.includes('特价')) {
    return 'danger'
  }
  if (reason.includes('涨价') || reason.includes('上涨')) {
    return 'warning'
  }
  if (reason === '当前价格') {
    return 'success'
  }
  return 'info'
}
</script>

<style scoped>
.price-history-view {
  min-height: 100vh;
  background: #f5f7fa;
}

.page-header {
  background: white;
  padding: 20px 30px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.header-content h2 {
  margin: 0 0 10px 0;
  color: #303133;
}

.el-main {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.loading-container {
  padding: 20px;
  background: white;
  border-radius: 8px;
}

.result-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.product-info-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.product-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-name {
  display: flex;
  align-items: center;
  gap: 15px;
}

.product-name h3 {
  margin: 0;
  font-size: 20px;
  color: white;
}

.current-price {
  font-size: 32px;
  font-weight: bold;
  color: #ffd700;
}

.chart-card,
.table-card {
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 500;
}

.price-value {
  color: #409eff;
  font-weight: 500;
}

.original-price {
  color: #909399;
  text-decoration: line-through;
}

.text-muted {
  color: #c0c4cc;
}

/* 响应式 */
@media (max-width: 768px) {
  .el-main {
    padding: 10px;
  }

  .product-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .product-name {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>

